package com.ayoldi.podcastusbsync.synchronizer;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.ayoldi.podcastusbsync.PodcastUSBSync;
import com.ayoldi.podcastusbsync.configurator.ConfigurationManager;
import com.ayoldi.podcastusbsync.configurator.ConfigurationUtils;
import com.ayoldi.podcastusbsync.downloader.FeedsDownloaderThread;
import com.ayoldi.podcastusbsync.model.Configuration;
import com.ayoldi.podcastusbsync.model.Configuration.UsbDeviceConfiguration;

public class USBDeviceSynchronizerManager {

	static Logger LOG = Logger.getLogger(USBDeviceSynchronizerManager.class);
	
	ConfigurationManager configurationManager;
	List<USBDeviceCheckerThread> usbDeviceCheckerThreads;
	
	
	long pollingUSBInterval=50000;
	
	public USBDeviceSynchronizerManager (ConfigurationManager configurationManager){
		this.configurationManager=configurationManager;
	}
	
	public void startDevicesSynchronizer(){
		
		try{
			pollingUSBInterval=Long.parseLong(configurationManager.getGlobalOptions().getUSBMonitorPeriod())*1000;
		}
		catch (Exception e){
			e.printStackTrace();
			LOG.warn("Could not parse usb monitor period: "+configurationManager.getGlobalOptions().getUSBMonitorPeriod());
		}		
		
		List<UsbDeviceConfiguration> devicesConfig= configurationManager.getUsbDeviceConfigurations();
		usbDeviceCheckerThreads=new ArrayList<USBDeviceCheckerThread>();
		for (UsbDeviceConfiguration deviceConfig : devicesConfig){
			USBDeviceSynchronizer synchronizer=new USBDeviceSynchronizer(configurationManager,deviceConfig);
			USBDeviceCheckerThread thread= new USBDeviceCheckerThread(synchronizer,pollingUSBInterval);
			thread.start();
			usbDeviceCheckerThreads.add(thread);
		}

	}

	public void stop() {
		for (USBDeviceCheckerThread thread : usbDeviceCheckerThreads){
			thread.setStopped(true);
		}
		boolean allThreadsStopped=false;
		while (!allThreadsStopped){
			allThreadsStopped=true;
			for (USBDeviceCheckerThread thread : usbDeviceCheckerThreads){
				if (!thread.isStopped()){
					allThreadsStopped=false;
				}
			}
			if (!allThreadsStopped){
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		
	}	
	
	
}
